import type { UserPromptTemplateVariables } from "@shared/triplit/types";
import { format as formatDateFn } from "date-fns";
import deepThinkingType from "./preset-prompt-templates/deep-thinking-type.json";
import terseAndEffectiveType from "./preset-prompt-templates/terse-and-effective-type.json";
import universalType from "./preset-prompt-templates/universal-type.json";
import { convertPresetJsonToText, replaceVar } from "./utils";

export const PRESET_VARIABLES: UserPromptTemplateVariables[] = [
  "input",
  "date",
  "time",
  "datetime",
  "now",
  "model_id",
];

export const PRESET_PROMPT_MAP = new Map([
  ["universal-type", JSON.stringify(universalType)],
  ["terse-and-effective-type", JSON.stringify(terseAndEffectiveType)],
  ["deep-thinking-type", JSON.stringify(deepThinkingType)],
  // ["translation-expert", JSON.stringify(translationExpert)],
]);

// Pre-compute and cache all preset text versions for better performance
export const PRESET_TEXT_CACHE = new Map<string, string>();
PRESET_PROMPT_MAP.forEach((jsonState, key) => {
  PRESET_TEXT_CACHE.set(key, convertPresetJsonToText(jsonState));
});

// Types for variable rendering
export type VariableRenderer = (
  template: string,
  handler?: () => string,
) => { replaced: string; value: string };

export type PresetVariableDef = {
  renderTemplate: VariableRenderer;
};

export const PRESET_VARIABLES_MAP = new Map<string, PresetVariableDef>([
  [
    "input",
    {
      // Without external context, default to empty string.
      renderTemplate: (template, handler) =>
        replaceVar(template, "input", handler?.() ?? ""),
    },
  ],
  [
    "date",
    {
      renderTemplate: (template) => {
        const d = new Date();
        return replaceVar(template, "date", formatDateFn(d, "yyyy-MM-dd"));
      },
    },
  ],
  [
    "time",
    {
      renderTemplate: (template) => {
        const d = new Date();
        return replaceVar(template, "time", formatDateFn(d, "HH:mm:ss"));
      },
    },
  ],
  [
    "datetime",
    {
      renderTemplate: (template) => {
        const d = new Date();
        return replaceVar(
          template,
          "datetime",
          formatDateFn(d, "yyyy-MM-dd HH:mm:ss"),
        );
      },
    },
  ],
  [
    "now",
    {
      renderTemplate: (template) => {
        const d = new Date();
        return replaceVar(
          template,
          "now",
          formatDateFn(d, "yyyy-MM-dd HH:mm:ss"),
        );
      },
    },
  ],
  [
    "model_id",
    {
      // Without external context, default to empty string.
      renderTemplate: (template, handler) =>
        replaceVar(template, "model_id", handler?.() ?? ""),
    },
  ],
]);
